package com.example.project.vo.writExcel;

import com.example.project.entity.GoodsBean;
import com.example.utils.date.DateUtils;
import com.example.utils.excel.ExcelUtils;
import com.example.utils.responseHeader.ResponseHeader;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;

public class WritExcel {

    /**
     * 商品导出
     * @param response
     * @param fileNameHeader 文件名头部（后缀名前面部分）
     * @param sheetName 工作簿名称
     * @param title 表格标题
     * @param column 表格列明
     * @param contentColumnNumber 内容列数量
     * @param goodsBeanList 导出得实体集合
     */
    public static void exportExcel(HttpServletRequest request, HttpServletResponse response, String fileNameHeader, String sheetName, String title, String[] column, int contentColumnNumber, List<GoodsBean> goodsBeanList) {
        //excel文件名
        String fileName = fileNameHeader + System.currentTimeMillis() + ".xls";

        //内容列数
        String [][] content = new String[goodsBeanList.size()][contentColumnNumber];
        for (int i = 0; i < goodsBeanList.size(); i++) {
            content[i] = new String[column.length];
            GoodsBean obj = goodsBeanList.get(i);
            content[i][0] = obj.getId().toString();
            content[i][1] = obj.getGoodsName();
            content[i][2] = obj.getGoodsPrice().toString();
            content[i][3] = obj.getGoodsPlaceOfProduction();
            content[i][4] = obj.getGoodsIntroduce();
            content[i][5] = DateUtils.parseDateToStr("yyyy-MM-dd",obj.getBookDate());
            content[i][6] = DateUtils.parseDateToStr("yyyy-MM-dd",obj.getCreateDate());
        }
        /**
         * 创建HSSFWorkbook
         * @param sheetName sheet名称
         * @param title 标题
         * @param column 列名
         * @param values 内容
         * @param wb HSSFWorkbook对象
         * @return
         */
        HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title,column,content, null);

        //响应到客户端
        try {
            ResponseHeader.setResponseHeader(request,response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
